﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using P2PLib.Client.DataModel;

namespace P2PLib.Client.Command
{
    public class CCResultCommand:CCCommandBase
    {
        private List<CFileInfo> files;
        //在写到流里时先写入list的大小
        public CCResultCommand() 
        :base(CCCommandType.Result)
        {
            this.files = new List<CFileInfo>();
        }
        public CCResultCommand(List<CFileInfo> list)
            :base(CCCommandType.Result)
        {
            this.files = list;
        }
        public List<CFileInfo> Files {
            set {
                this.files = value;
            }
            get {
                return this.files;
            }
        }
        public override void ReadFromStream(System.IO.Stream stream)
        {
            byte[] buffer = new byte[4];
            stream.Read(buffer, 0, 4);
            int size = BitConverter.ToInt32(buffer, 0);
            files = new List<CFileInfo>();
            for (int i = 0; i < size; i++) {
                CFileInfo cf = new CFileInfo();
                stream.Read(buffer, 0, 4);
                int hashSize = BitConverter.ToInt32(buffer, 0);
                buffer = new byte[hashSize];
                stream.Read(buffer, 0, hashSize);
                cf.FileHashCode = Encoding.ASCII.GetString(buffer);
                buffer = new byte[4];
                stream.Read(buffer, 0, 4);
                int nameSize = BitConverter.ToInt32(buffer, 0);
                buffer = new byte[nameSize];
                stream.Read(buffer, 0, nameSize);
               
                cf.FileName = Encoding.UTF8.GetString(buffer);
                buffer = new byte[8];
                stream.Read(buffer,0,8);
                cf.FileSize = BitConverter.ToInt64(buffer, 0);
                files.Add(cf);
                GC.Collect();
            }
        }
        public override void WriteToStream(System.IO.Stream stream)
        {
            byte[] buffer = new byte[4];
            buffer = BitConverter.GetBytes(files.Count);
            stream.Write(buffer, 0, 4);
            foreach (CFileInfo cf in files) {
                string hash = cf.FileHashCode;
                buffer = Encoding.ASCII.GetBytes(hash);
                int hashSize = buffer.Length;
                stream.Write(BitConverter.GetBytes(hashSize), 0, 4);
                stream.Write(buffer, 0, buffer.Length);
                string name = cf.FileName;
                buffer = Encoding.UTF8.GetBytes(name);
                int nameSize = buffer.Length;
                stream.Write(BitConverter.GetBytes(nameSize), 0, 4);
                stream.Write(buffer, 0, nameSize);
                long fileSize = cf.FileSize;
                stream.Write(BitConverter.GetBytes(fileSize), 0, 8);
            }
        }
    }

}
